package com.aizuda.easyManagerTool.sdk.docker;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Arrays;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;


public class APIHttpTemplate {


    public String POST(HttpPost httpGet, Consumer<HttpResponse> consumer) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if(!Arrays.asList(200,202).contains(statusCode)){
            throw new RuntimeException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity entity = response.getEntity();
        consumer.accept(response);
        httpClient.close();
        return EntityUtils.toString(entity);
    }


    public <T> T BASE(HttpRequestBase httpRequestBase, BiFunction<HttpResponse,String,T> consumer) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpRequestBase);
        int statusCode = response.getStatusLine().getStatusCode();
        if(!Arrays.asList(200,202).contains(statusCode)){
            throw new RuntimeException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity entity = response.getEntity();
        T obj = consumer.apply(response,EntityUtils.toString(entity));
        httpClient.close();
        return obj;
    }

    public String BASE(HttpRequestBase httpRequestBase) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpRequestBase);
        int statusCode = response.getStatusLine().getStatusCode();
        if(!Arrays.asList(200,202).contains(statusCode)){
            throw new RuntimeException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity entity = response.getEntity();
        httpClient.close();
        return EntityUtils.toString(entity);
    }

}
